<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <table border="1">
      <thead>
        <tr>
          <th><input type="checkbox" id="all" />全选</th>
          <th>1</th>
          <th>2</th>
          <th>3</th>
          <th>4</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type="checkbox" name="box" /></td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="box" /></td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="box" /></td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
        </tr>
        <tr>
          <td><input type="checkbox" name="box" /></td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
          <td>1</td>
        </tr>
      </tbody>
    </table>
  </body>
  <script>
    window.onload = function () {
      //全选复选框

      //tbody内的复选框
      var boxObj = document.getElementsByName('box')
      //给全选框 绑定值改变事件
      document.getElementById('all').addEventListener('change', function () {
        //循环普通的复选框 将普通的复选框值和全选的复选框值保持一致
        for (let i = 0; i < boxObj.length; i++) {
          boxObj[i].checked = this.checked
        }
      })
      //子复选框
      //循环所有的子复选框
      for (let i = 0; i < boxObj.length; i++) {
        //给每个子复选框 加上绑定值改变事件
        boxObj[i].addEventListener('change', function () {
          var flag = true //声明定义 默认为true
          //循环每一个子复选框
          for (let j = 0; j < boxObj.length; j++) {
            //判断 只要有一个为 没选中 false
            if (!boxObj[j].checked) {
              flag = false
            }
          }
          //最后把值给到 全选框
          document.getElementById('all').checked = flag
        })
      }
    }
  </script>
</html>
